var watchElements = "input,select,textarea";

/**
 * 폼 변경 감지를 위한 원본값을 hash에 저장한다.
 * @param form 폼id selector
 * @param ignore 변경감지 제외 컨트롤 selector
 */
var watchChanged = function(form, ignoreElements) {
	try{
		if($(form).length == 0) {
			throw new Error("Invalid form selector");
		}
		// 원본데이터 저장
		if(ignoreElements) {
			$(form + " " + ignoreElements).each(function() {
				$(this).addClass("ignore-changed");
			});	
		}
		console.log("------------- call watchChanged serialize -----------------");
		var data = $(form + " "+watchElements).not(".ignore-changed").serialize();
		console.log(data);
		
		
	    $(form).data("hash", data);
		
	} catch(e) {
		alert("Javascript Error: " + e.message);
	} finally{}
}; 


/**
 * 폼 변경여부를 리턴한다.
 * @param form 폼id selector
 * @param objcallback callback object
 */
var isChanged = function (form, objcallback) {
	var changed = false;
	try{
		if($(form).length == 0) {
			throw new Error("Invalid form selector");
		}    
		
		console.log("------------- call isChanged serialize -----------------");
		var data = $(form + " "+watchElements).not(".ignore-changed").serialize();
		console.log(data);
		
		if ($(form).data("hash") !== data) {
			changed = true;
		}	
		
		changed? objcallback["changed"]():objcallback["unchanged"]();
		
	} catch(e) {
		alert("Javascript Error: " + e.message);
	} finally{}	    
};


/**
 * 코드리스트를 select박스에 셋업한다.
 * @param selector select컨트롤 selector
 * @param data data 
 * @param state state 
 * @param append select컨트롤 선택옵션 추가 여부(ex.--선택하세요--). boolean
 * @param selectedValue select컨트롤 옵션 선택값
 */
var respCodeSelect = function(selector, data, state, append, selectedValue) {
    console.log("--- callback success ---");
    console.log("data: " + data);
    console.log("state: " + state);
    
    var _append = append || false;
    if(_append) {
    	$(selector).append('<option value="" selected>-- 선택 --</option>');
    }
    
    $.each(data, function(index, element) {
    	var _selectedValue = selectedValue || ''; 
    	var selected = (element.CD_DATA == _selectedValue ? "selected":""); 
    	
    	$(selector).append("<option value='" + element.CD_DATA+"' " + selected +" >" + 
            element.CD_NM + 
            "</option>");
    }); 
    
    
}; 

//********************************************************
//form validation area   
//******************************************************** 
$(function() {
	// rule name: compareDate 
	// desc: fromdate todate 날짜비교 
	// params: {fromDate:selector, toDate:selector}
	$.validator.addMethod("compareDate", function(value, element, params) {
		var fromDate = $(params.fromDate).val().replace(/[\/]|[\-]|[.]/gi,"") || '00000000';
		var toDate = $(params.toDate).val().replace(/[\/]|[\-]|[.]/gi,"") || '99991231';
		return fromDate <= toDate; 
	}, "시작일자가 종료일자보다 클수 없습니다.");
});

/**
* validate rules 추가 
*/
var addDefaultRules = function(elements, label) {
  elements.each(function() {
      $(this).rules("add", {
          required: true,
          messages: {required: formatStr("{0}은(는) 필수입력입니다.",label) }
      });         
  });
};

/**
* validate rules 제거
*/
var removeDefaultRules = function(elements) {
  elements.each(function() {
      $(this).rules("remove", "required");         
  });
}; 

/**
* validate rules 추가 
*/
var addOptionRules = function(elements, label, options) {
  elements.each(function() {
      $(this).rules("add", options);         
  });
};
 
/**
* Validate object
*/
var ValidateRules = function() {
 /**
 * Validate object
 * @param selector 셀렉터문자열
 * @param label 라벨
 * @options 옵션object
 */
 this.addRules = function(selector, label, options) {
	 if(options) {
		 addOptionRules($(selector), label, options);
	 } else { // 기본required룰만 추가
		 addDefaultRules($(selector), label);
	 }
	 
 };
 this.removeRules = function(selector) {
     removeDefaultRules($(selector));
 };
}; 


//********************************************************
//exception processing area   
//******************************************************** 
/**
* 에러다이얼로그 오픈
*/
var viewError = function(response) {
	$('<div title=" Error"></div>').dialog({
		width:700,
		height:600,
        autoOpen: true,
        modal: false,
        open: function() {
           $(this).html(response)
        },
        buttons: {
           'Close': function() { $(this).dialog('destroy'); }
        }
    });
};

